import { fileURLToPath, URL } from 'node:url'
import path from 'node:path'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver} from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default ({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())
  return defineConfig({
    base: './',
    server: {
      open: true,
      port: 9000,
      proxy: {
        '/proxy': {
          target: env.VITE_APP_API_BASEURL,
          changeOrigin: command === 'serve' && env.VITE_OPEN_PROXY == 'true',
          rewrite: path => path.replace(/\/proxy/, '')
        }
      }
    },
    build: {
      sourcemap: env.VITE_BUILD_SOURCEMAP == 'true',
      terserOptions: {
        compress: {
          drop_console: env.VITE_BUILD_DROP_CONSOLE == 'true'
        }
      }
    },
    plugins: [
      vue(),
      AutoImport({
        // 自动导入 Vue @vueuse/core vue-router相关函数
        imports: [
          'vue',
          'vue-router',
          'pinia',
		  '@vueuse/core',
          {
            //未被自动导入的在这里补充
            'vue-router': ['stringifyQuery', 'createRouter', 'createWebHashHistory'],
            /* 自定义模块 */
            // '~/api': [['default', 'api']],
            '~/utils': [['default', 'utils']]
          }],
        resolvers: [
          // 自动导入AntDesignVue相关函数
          AntDesignVueResolver()
        ],
      }),
      Components({
        dirs: ['src/components'],
        resolvers: [
          // 自动导入AntDesignVue 组件
          AntDesignVueResolver({resolveIcons:true})
        ],
      })
    ],
    resolve: {
      alias: {
        '~': fileURLToPath(new URL('./src', import.meta.url))
      }
    }
  })
}
